package thread;

class MyBlockingQueue{
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private static Object locker = new Object();
    public MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }
    public void put(String s) throws InterruptedException {
        synchronized (locker){
            while (size >= elems.length){
                locker.wait();
            }
            elems[tail] = s;
            tail++;
            if(tail >= elems.length){
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }
    public String take() throws InterruptedException {
        String s = null;
        synchronized (locker){
            while (size == 0){
                locker.wait();
            }

            s = elems[head];
            head++;
            if(head >= elems.length){
                head = 0;
            }
            size--;
            locker.notify();
        }
        return s;
    }
}

public class ThreadDemo22 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue(10);
        //生产者
        Thread t1 = new Thread(() ->{
            int n = 0;
            while(true){
                try {
                    queue.put(n + "");
                    System.out.println("生产元素" + n);
                    n++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        // 消费者
        Thread t2 = new Thread(() ->{
           while(true){
               try {
                   String elem = queue.take();
                   System.out.println("消费了" + elem);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        t1.start();
        t2.start();
    }
}
